#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File ：CartLogic.py
@Author ：zqy
@Email : zqingy@work@163.com 
@note: 
"""
from typing import List, Dict

from flask import g

from application.exception.BasicException import BasicException
from application.Parser.CartParser import CartValidator
from application.enumeration.StatusCodeEnum import StatusCodeEnum
from application.logic import BaseLogic
from application.mapper.CartMapper import CartMapper
from application.model.OrderModel import CartItem
from application.util.MysqlUtil import mysql_session


class CartLogic(BaseLogic):
    """
    购物车逻辑类
    """
    model: CartItem = CartItem  # 定义模型
    mapper: CartMapper = CartMapper  # 定义mapper
    # 实例化redis客户端
    validator: CartValidator = CartValidator

    @classmethod
    def add(cls, params):
        """
        添加购物车
        :return:
        """
        assert params["quantity"] > 0, "数量不能小于0"
        params["user_id"] = g.user.id
        # 判断是否已经存在
        cart_item: CartItem = cls.model.query.filter_by(user_id=params["user_id"],product_id=params["product_id"]).first()
        if cart_item:
            cart_item.quantity += params["quantity"]
            cart_item.selected = True
            try:
                mysql_session.add(instance=cart_item)
                mysql_session.commit()
            except Exception as e:
                mysql_session.rollback()
                raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="添加购物车失败，请稍后再试")
        else:
            cart_item: CartItem = CartItem(**params)
            if not cls.mapper.insert(model=cart_item):
                raise BasicException(status_code=StatusCodeEnum.ERROR.value, error_message="添加购物车失败，请稍后再试")
        # return cart_item.to_dict()

    @classmethod
    def get_list(cls, params) -> list:
        """
        获取购物车列表
        :return:
        """
        return cls.mapper.get_cart_item_by_user_id(g.user.id)
